<?php

namespace MoChat\App\Statistic\Action\FollowUp;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Arr;
use MoChat\App\Client\Constants\ClientFollowRecordTypeCode;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 跟进统计列表
 * @Controller
 */
class Index extends AbstractAction
{
    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticFollowUp/index", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $follow = Db::table('client_follow_record')
            ->select('*');
        $follow1 = Db::table('client_follow_record')
            ->where('type',ClientFollowRecordTypeCode::PHONE)
            ->select('*');
        $follow2 = Db::table('client_follow_record')
            ->where('type',ClientFollowRecordTypeCode::INTERVIEW)
            ->select('*');
        $follow3 = Db::table('client_follow_record')
            ->where('type',ClientFollowRecordTypeCode::WECHAT)
            ->select('*');

        $list = Db::table('work_employee as employee')
            ->leftJoinSub($follow, 'follow', 'follow.user_id', '=','employee.id')
            ->leftJoinSub($follow1, 'follow_1', 'follow_1.user_id', '=','employee.id')
            ->leftJoinSub($follow2, 'follow_2', 'follow_2.user_id', '=','employee.id')
            ->leftJoinSub($follow3, 'follow_3', 'follow_3.user_id', '=','employee.id')
            ->leftJoin('work_department as dept', 'dept.id', '=', 'employee.main_department_id')
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['deptId']), function ($query) use ($data) {
                $query->where('dept.id', $data['deptId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('follow.followed_at', [$data['startTime'], $data['endTime']]);
            })->when(!empty($data['orderBy']),function ($query)use($data){
                $orderString='';
                $data['orderBy']=json_decode($data['orderBy'],true);
                foreach ($data['orderBy'] as $key=>$datum){
                    if ($datum){
                        $datum=$datum=='ascend'?'asc':'desc';
                        $orderString.=$orderString?','.$key.' '.$datum:$key.' '.$datum;
                    }
                }
                if ($orderString){
                    $query->orderByRaw($orderString);
                }
            })
            ->select([
                'employee.id',
                'employee.name',
                'dept.name as deptName',
                Db::raw('COUNT(DISTINCT mc_follow.client_id) as totalFollowUpNumber'),
                Db::raw('COUNT(DISTINCT mc_follow_1.client_id) as callFollowUpNumber'),
                Db::raw('COUNT(DISTINCT mc_follow_2.client_id) as interviewFollowUpNumber'),
                Db::raw('COUNT(DISTINCT mc_follow_3.client_id) as wechatFollowUpNumber'),
            ])->groupBy([
                'employee.id'
            ])->paginate();
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list['data'])) {
            //呼叫跟进家数合计
            $list['totalCallFollowUpNumber'] = array_sum(array_column($list['data'], 'callFollowUpNumber'));
            // 面访跟进家数合计
            $list['totalInterviewFollowUpNumber'] = array_sum(array_column($list['data'], 'interviewFollowUpNumber'));
            //企微跟进家数合计
            $list['totalWechatFollowUpNumber'] = array_sum(array_column($list['data'], 'wechatFollowUpNumber'));
            //总跟进家数合计
            $list['totalFollowUpNumberAll'] = array_sum(array_column($list['data'], 'totalFollowUpNumber'));
        }
        return $list;
    }

    /**
     * @param $data
     * @return int
     */
    private function interviewFollow($data): int
    {
        return Db::table('client_follow_record as follow')
            ->leftJoin('work_employee as employee', 'employee.id', '=', 'follow.user_id')
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('follow.followed_at', [$data['startTime'], $data['endTime']]);
            })
            ->where('follow.type', ClientFollowRecordTypeCode::INTERVIEW)
            ->count(Db::raw('DISTINCT mc_follow.client_id'));
    }
}
